import { createRouter, createWebHistory } from "vue-router";
import Home from "/src/views/Home.vue";
import Play from "/src/views/Play.vue";
import Community from "/src/views/Community.vue";
import Favorites from "/src/views/Favorites.vue";
import Login from "/src/views/Login.vue";
import Profile from "../views/Profile.vue";
import Manage from "../views/Manage.vue";
import { checkLogin } from "@/utils/auth";

const routes = [
	{ path: "/", name: "Home", component: Home, meta: { showLoader: true } },
	{
		path: "/play",
		name: "Play",
		component: Play,
		meta: { showLoader: true },
		meta: { requiresAuth: true },
	},
	{
		path: "/community",
		name: "Community",
		component: Community,
		meta: { requiresAuth: true },
	},
	{
		path: "/favorites",
		name: "Favorites",
		component: Favorites,
		meta: { requiresAuth: true },
	},
	{
		path: "/login",
		name: "Login",
		component: Login,
		meta: { layout: "login" }, // ✅ 用 meta 标记 login 页面
	},
	{
		path: "/profile",
		name: "Profile",
		component: Profile,
		meta: { requiresAuth: true },
	},
	{
		path: "/manage",
		name: "Manage",
		component: Manage,
		meta: { requiresAuth: true },
	},
	
];

const router = createRouter({
	history: createWebHistory(),
	routes,
});

router.beforeEach(async (to, from, next) => {
	const isAuthenticated = await checkLogin();
	if (to.meta.requiresAuth && !isAuthenticated) {
		next("/login");
	} else if (to.path === "/login" && isAuthenticated) {
		next("/");
	} else {
		next();
	}
});

export default router;
